import { NotFound, BadRequest } from 'http-errors'
import Role from '@/database/models/role'

const getRoles = async () => {
  const roles = await Role.findAll({
    order: [
      ['rank', 'ASC'],
      ['id', 'ASC'],
    ],
  })
  return roles
}

const getRoleInfo = async (id: number) => {
  const role = await getRole(id)
  return role
}

const addRole = async (body: Body) => {
  const { name, durationMonths, price, rank, desc } = body
  const role = await Role.create({
    name,
    durationMonths,
    price,
    rank,
    desc,
  })
  return role
}

const updateRole = async (id: number, body: Body) => {
  const { name, durationMonths, price, rank, desc } = body
  const role = await getRole(id)
  await role.update({
    name,
    durationMonths,
    price,
    rank,
    desc,
  })
}

const deleteRole = async (id: number) => {
  const role = await getRole(id)
  await role.destroy()
}

/**
 * 公共方法：查询当前角色
 */
async function getRole(id: number) {
  if (!id) {
    throw new BadRequest('角色id不能为空。')
  }
  const role = await Role.findByPk(id)
  if (!role) {
    throw new NotFound(`ID: ${id}的角色未找到。`)
  }
  return role
}

export default {
  getRoles,
  getRoleInfo,
  addRole,
  updateRole,
  deleteRole,
  getRole,
}
